package com.yupi.yuoj.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.yupi.yuoj.common.BaseResponse;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.common.ResultUtils;
import com.yupi.yuoj.model.entity.CompileInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
//@ConfigurationProperties(prefix = "mail")
public class EmailUtil {
    // 邮件服务器的SMTP地址，可选，默认为smtp.<发件人邮箱后缀>
    @Value("${mail.host}")
    private String host;

    // 邮件服务器的SMTP端口，可选，默认25
    @Value("${mail.port}")
    private int port;

    // 发件人（必须正确，否则发送失败）
    @Value("${mail.from}")
    private String fromEmailAddress;

    // 用户名，默认为发件人邮箱前缀
    @Value("${mail.user}")
    private String user;

    // 密码（注意，某些邮箱需要为SMTP服务单独设置授权码)
    @Value("${mail.pass}")
    private String password;

    @Value("${mail.subject}")
    private String subject;

    @Value("${mail.buildNotice}")
    private String buildNotice;

    @Value("${mail.contentPre}")
    private String contentPre;

    @Value("${mail.contentEnd}")
    private String contentEnd;

    private MailAccount getMailCount() {
        MailAccount account = new MailAccount();
        account.setHost(host);
        account.setPort(port);
        account.setAuth(true);
        account.setFrom(fromEmailAddress);
        account.setUser(user);
        account.setPass(password);
        account.setSslEnable(true);
        return account;
    }

    /**
     * 发送普通邮件
     *
     * @param toMail 收件人
     * @param code   标题
     */
    public void sendNormalEmail(String toMail, String code) {
        MailAccount account = getMailCount();
        ArrayList<String> mailList = CollUtil.newArrayList(
                toMail);
        String send = MailUtil.send(account, mailList, subject,
                "<h2> " + contentPre + code + contentEnd + "</h2>", true);
        log.info("发送状态id --->" + send);
    }

    public BaseResponse<Object> sendNormalEmail(CompileInfo info) {
        List<String> toEmailAddress = info.getToEmailAddress();
        if (CollUtil.isEmpty(toEmailAddress)) {
            ResultUtils.error(ErrorCode.OPERATION_ERROR, "接收邮箱不能空！");
        }
        MailAccount account = getMailCount();
        String send = MailUtil.send(account, toEmailAddress, buildNotice,
                info.getMessage(), true);
        log.info("发送状态id --->" + send);
        return ResultUtils.success("发送状态id = " + send);
    }

}
